import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by wuhainan on 2017/2/21.
 */
public class UserDao {
    public User getByUserName(Connection connection,String userName) throws SQLException {
        User resultUser=null;
        String sql=" select * from t_user where userName=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        ResultSet resultSet= preparedStatement.executeQuery();
        if(resultSet.next()){
            resultUser=new User();
            resultUser.setId(resultSet.getInt("id"));
            resultUser.setUserName(resultSet.getString("userName"));
            resultUser.setPassword(resultSet.getString("password"));
        }
        return resultUser;

    }

    public Set<String> getRoles(Connection connection, String userName) throws SQLException {
        Set<String> roles=new HashSet<String>();
        String sql=" SELECT * FROM t_user u,t_role r WHERE u.roleId=r.id and u.userName=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        ResultSet resultSet= preparedStatement.executeQuery();
        while (resultSet.next()){
            roles.add(resultSet.getString("roleName"));
        }
        return roles;
    }

    public Set<String> getPermissions(Connection connection, String userName) throws SQLException {
        Set<String> permissions=new HashSet<String>();
        String sql=" SELECT * FROM t_permission p,t_user u,t_role r WHERE u.roleId=r.id " +
                "and p.roleId=r.id and u.userName=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,userName);
        ResultSet resultSet= preparedStatement.executeQuery();
        while (resultSet.next()){
            permissions.add(resultSet.getString("permissionName"));
        }
        return permissions;
    }
}
